<template>
	<view class="container">
		<!-- 表单区域 -->
		<view class="form-section">
			<q-field 
				label="圈子名称" 
				v-model="form.name" 
				:required="true" 
				placeholder="请填写圈子名称"
				@input="validateName"
			></q-field>
			
			<q-field 
				label="圈子介绍" 
				type="textarea" 
				v-model="form.description" 
				:required="true" 
				placeholder="请填写圈子介绍，至少10个字符"
				@input="validateDescription"
			></q-field>
			
			<view class="form-item">
				<view class="label">
					<text>圈子头像</text>
					<text class="required">*</text>
				</view>
				<view class="upload-container">
					<q-upload 
						:maxCount="1" 
						:file="coverMediaList" 
						ref="coverUpload" 
						@success="coverSuccess"
						:autoUpload="true"
						:topicAvatar="true"
					></q-upload>
					<text class="upload-tip">建议尺寸：1:1，支持jpg、png格式</text>
				</view>
			</view>
			
			<view class="form-item">
				<view class="label">
					<text>圈子背景</text>
					<text class="required">*</text>
				</view>
				<view class="upload-container">
					<q-upload 
						:maxCount="1" 
						:file="bgMediaList" 
						ref="bgUpload" 
						@success="bgSuccess"
						:autoUpload="true"
						:topicBg="true"
					></q-upload>
					<text class="upload-tip">建议尺寸：16:9，支持jpg、png格式</text>
				</view>
			</view>
		</view>
		
		<!-- 提交按钮 -->
		<view class="submit-section">
			<q-button 
				shape="circle" 
				@click="submit"
				:disabled="isSubmitting"
			>
				{{ isSubmitting ? '保存中...' : '保存' }}
			</q-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 表单数据
				form: {
					id: '',
					name: '',
					description: '',
					cover_image: '',
					bg_image: ''
				},
				// 上传文件列表
				coverMediaList: [],
				bgMediaList: [],
				// 状态控制
				isSubmitting: false,
				isLoading: true,
				// 验证错误信息
				validationErrors: {
					name: '',
					description: '',
					cover_image: '',
					bg_image: ''
				}
			};
		},
		computed: {
			header() {
				return {
					token: this.$store.state.user.userInfo.token
				};
			}
		},
		onLoad(options) {
			if (options.id) {
				this.form.id = options.id;
				this.getTopicInfo(options.id);
			} else {
				this.$u.toast('缺少圈子ID参数');
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		},
		
		onShow() {
			// 设置导航栏标题
			uni.setNavigationBarTitle({
				title: '编辑圈子信息'
			});
		},
		methods: {
			/**
			 * 提交表单
			 */
			async submit() {
				// 防重复提交
				if (this.isSubmitting) {
					return;
				}
				
				// 表单验证
				if (!this.validateForm()) {
					return;
				}
				
				try {
					this.isSubmitting = true;
					uni.showLoading({
						title: '保存中...',
						mask: true
					});
					
					const res = await this.$H.post('topic/saveInfo', this.form);
					
					if (res.code === 200) {
						uni.hideLoading();
						this.$u.toast('保存成功');
						
						setTimeout(() => {
							uni.navigateBack();
						}, 1000);
					} else {
						uni.hideLoading();
						this.$u.toast(res.msg || '保存失败，请重试');
					}
				} catch (error) {
					console.error('保存圈子信息失败:', error);
					uni.hideLoading();
					this.$u.toast('网络错误，请检查网络连接');
				} finally {
					this.isSubmitting = false;
				}
			},
			
			/**
			 * 表单验证
			 */
			validateForm() {
				let isValid = true;
				
				// 重置错误信息
				this.resetValidationErrors();
				
				// 验证圈子名称
				if (!this.form.name || this.form.name.trim() === '') {
					this.validationErrors.name = '请填写圈子名称';
					this.$u.toast('请填写圈子名称');
					isValid = false;
				} else if (this.form.name.length > 20) {
					this.validationErrors.name = '圈子名称不能超过20个字符';
					this.$u.toast('圈子名称不能超过20个字符');
					isValid = false;
				}
				
				// 验证圈子介绍
				if (!this.form.description || this.form.description.trim() === '') {
					this.validationErrors.description = '请填写圈子介绍';
					if (isValid) this.$u.toast('请填写圈子介绍');
					isValid = false;
				} else if (this.form.description.length < 10) {
					this.validationErrors.description = '圈子介绍至少需要10个字符';
					if (isValid) this.$u.toast('圈子介绍至少需要10个字符');
					isValid = false;
				} else if (this.form.description.length > 200) {
					this.validationErrors.description = '圈子介绍不能超过200个字符';
					if (isValid) this.$u.toast('圈子介绍不能超过200个字符');
					isValid = false;
				}
				
				// 验证圈子头像
				if (!this.form.cover_image) {
					this.validationErrors.cover_image = '请上传圈子头像';
					if (isValid) this.$u.toast('请上传圈子头像');
					isValid = false;
				}
				
				// 验证圈子背景
				if (!this.form.bg_image) {
					this.validationErrors.bg_image = '请上传圈子背景';
					if (isValid) this.$u.toast('请上传圈子背景');
					isValid = false;
				}
				
				return isValid;
			},
			
			/**
			 * 重置验证错误信息
			 */
			resetValidationErrors() {
				this.validationErrors = {
					name: '',
					description: '',
					cover_image: '',
					bg_image: ''
				};
			},
			
			/**
			 * 验证圈子名称
			 */
			validateName() {
				if (this.form.name && this.form.name.length > 20) {
					this.form.name = this.form.name.substring(0, 20);
					this.$u.toast('圈子名称不能超过20个字符');
				}
			},
			
			/**
			 * 验证圈子介绍
			 */
			validateDescription() {
				if (this.form.description && this.form.description.length > 200) {
					this.form.description = this.form.description.substring(0, 200);
					this.$u.toast('圈子介绍不能超过200个字符');
				}
			},
			/**
			 * 头像上传成功回调
			 */
			coverSuccess(e) {
				if (e && e.length > 0 && e[0].url) {
					this.form.cover_image = e[0].url;
					this.validationErrors.cover_image = '';
					this.$u.toast('头像上传成功');
				} else {
					this.$u.toast('头像上传失败，请重试');
				}
			},
			
			/**
			 * 背景上传成功回调
			 */
			bgSuccess(e) {
				if (e && e.length > 0 && e[0].url) {
					this.form.bg_image = e[0].url;
					this.validationErrors.bg_image = '';
					this.$u.toast('背景上传成功');
				} else {
					this.$u.toast('背景上传失败，请重试');
				}
			},
			/**
			 * 获取圈子信息
			 */
			async getTopicInfo(topicId) {
				try {
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
					
					const res = await this.$H.get('topic/detail', {
						id: topicId
					});
					
					if (res.code === 200 && res.result) {
						// 设置表单数据
						this.form = {
							id: res.result.id || topicId,
							name: res.result.name || '',
							description: res.result.description || '',
							cover_image: res.result.cover_image || '',
							bg_image: res.result.bg_image || ''
						};
						
						// 设置头像预览
						if (res.result.cover_image) {
							this.coverMediaList = [{
								url: this.$utils.imgPath(res.result.cover_image)
							}];
						}
						
						// 设置背景预览
						if (res.result.bg_image) {
							this.bgMediaList = [{
								url: this.$utils.imgPath(res.result.bg_image)
							}];
						}
						
						uni.hideLoading();
					} else {
						uni.hideLoading();
						this.$u.toast(res.msg || '获取圈子信息失败');
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}
				} catch (error) {
					console.error('获取圈子信息失败:', error);
					uni.hideLoading();
					this.$u.toast('网络错误，请检查网络连接');
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} finally {
					this.isLoading = false;
				}
			}
		}
	};
</script>

<style>
	page {
		background-color: #f8f9fa;
	}
</style>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		padding-bottom: 120rpx;
	}
	
	.form-section {
		padding: 20rpx 0;
	}
	
	.form-item {
		background-color: #ffffff;
		margin: 20rpx 30rpx;
		padding: 30rpx;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
		border: 1rpx solid #f0f0f0;
		transition: all 0.3s ease;
		
		&:hover {
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
		}

		.label {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;
			font-size: 32rpx;
			font-weight: 600;
			color: #333333;
			
			.required {
				color: #ff4757;
				margin-left: 8rpx;
				font-size: 28rpx;
			}
		}
		
		.upload-container {
			.upload-tip {
				display: block;
				margin-top: 16rpx;
				font-size: 24rpx;
				color: #999999;
				line-height: 1.4;
			}
		}
	}
	
	.submit-section {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		padding: 20rpx 30rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		border-top: 1rpx solid #f0f0f0;
		box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.04);
		z-index: 100;
		
		:deep(.button) {
			width: 100%;
			height: 88rpx;
			line-height: 88rpx;
			font-size: 32rpx;
			font-weight: 600;
			background: linear-gradient(135deg, #465cff 0%, #5a6cff 100%);
			border-radius: 44rpx;
			box-shadow: 0 8rpx 24rpx rgba(70, 92, 255, 0.3);
			transition: all 0.3s ease;
			
			&:disabled {
				background: #cccccc;
				box-shadow: none;
				color: #999999;
			}
			
			&:not(:disabled):active {
				transform: translateY(2rpx);
				box-shadow: 0 4rpx 12rpx rgba(70, 92, 255, 0.2);
			}
		}
	}
	
	/* 优化q-field组件样式 */
	:deep(.m-field) {
		background-color: #ffffff;
		margin: 20rpx 30rpx;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
		border: 1rpx solid #f0f0f0;
		transition: all 0.3s ease;
		
		&:focus-within {
			border-color: #465cff;
			box-shadow: 0 4rpx 20rpx rgba(70, 92, 255, 0.1);
		}
		
		.label {
			font-weight: 600;
			color: #333333;
			font-size: 32rpx;
			
			.required {
				color: #ff4757;
				font-size: 28rpx;
			}
			
			.field-body {
				background-color: #f8f9fa;
				border: 1rpx solid #e9ecef;
				border-radius: 12rpx;
				padding: 24rpx;
				margin-top: 16rpx;
				transition: all 0.3s ease;
				
				&:focus-within {
					background-color: #ffffff;
					border-color: #465cff;
					box-shadow: 0 0 0 3rpx rgba(70, 92, 255, 0.1);
				}
				
				.input, textarea {
					font-size: 28rpx;
					color: #333333;
					line-height: 1.5;
				}
				
				textarea {
					min-height: 120rpx;
				}
			}
		}
	}
	
	/* 响应式设计 */
	@media screen and (max-width: 750rpx) {
		.form-item {
			margin: 16rpx 20rpx;
			padding: 24rpx;
		}
		
		:deep(.m-field) {
			margin: 16rpx 20rpx;
		}
		
		.submit-section {
			padding: 16rpx 20rpx;
			padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
		}
	}
	
	/* 加载动画 */
	.loading-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(255, 255, 255, 0.8);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9999;
		
		.loading-content {
			display: flex;
			flex-direction: column;
			align-items: center;
			
			.loading-spinner {
				width: 60rpx;
				height: 60rpx;
				border: 4rpx solid #f3f3f3;
				border-top: 4rpx solid #465cff;
				border-radius: 50%;
				animation: spin 1s linear infinite;
			}
			
			.loading-text {
				margin-top: 20rpx;
				font-size: 28rpx;
				color: #666666;
			}
		}
	}
	
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
</style>